
(function () {
    //新建角色，打开弹窗
	jQuery('.addBtn').on('click', function () {
		jQuery('#id').val('');
		var creator = localStorage.getItem('name');
		jQuery('#name').val('');
		jQuery('#description').val('');
		jQuery('#creator').val(creator);
		jQuery('#roleModal').modal('show');
	});
	///验证角色是否重复
	jQuery('#name').blur(function(){
		var name=jQuery("#name").val();
		var url=window.rootPath+"/ui/role/rolevalidate"+"?name="+name;
		jQuery.ajax({
			url:  encodeURI(url),
			cache:false,
            type: 'get',
            dataType: 'json',
            success: function (data) {
            	if(data.code==0){
            		$.springLemonDialog({
   	 		         content: '角色名称重复',// 确认文本
   	 		         clickButton: function (sender, modal, index) {// 按钮事件处理
   	 		             $(this).closeDialog(modal); 
   	 		         }
   	 		        });
            	}	
            }
        });	
	})
    
    /////角色的列表
    var serverData = {};
    var	serverTable;
    jQuery(document).ready(function () {
        serverTable=  jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url": window.rootPath+'/ui/role/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
	                data: null,
	                defaultContent: ""
                },
                {
                    data:null,
                    defaultContent: "",
                    render: function(data, type, full, meta){
                        var operate ='<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
                            +'<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>';

                        return operate;

                    }
                },
                {
                    data: 'name'
                },
                {
                    data: 'description'
                },
                {
                    data: 'creator'
                } 
              ],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }

                serverTable.off('click','tr');
                serverTable.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTable.row( this ).data();

                    if(target.className.indexOf('fa-remove')!=-1 || target.className.indexOf('delBtn')!=-1){

                        deleteRole(data);
                    }

                    if(target.className.indexOf('fa-pencil')!=-1||target.className.indexOf('editBtn')!=-1){

                        editRole(data);
                    }

                    return;
                } );
            }
        });
        var deleteRole=function(data){
            if(!data) return;
            $.springLemonDialog({
                content:'确认删除 '+data.name+'?',//确认文本
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if(index==0){
                        var url=window.rootPath+"/ui/role/delRole"+"?id="+data.id;
                        jQuery.ajax({
                            url:encodeURI(url),
                            cache:false,
                            type : "get",
                            dataType:"json",
                            success:function(data){
                                serverTable.draw(false);
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }

            });

        };
        var editRole=function(data){
            if(!data) return;
            jQuery('#id').val(data.id);
            jQuery('#name').val(data.name);
            jQuery('#description').val(data.description);
            jQuery('#creator').val(data.creator);
            jQuery('#roleModal').modal('show');
        };
        jQuery('.searchBtn').on('click',function(){
            serverData.key=jQuery('#keyword').val();
            serverTable.draw();
        })
        //撤销查询
        jQuery('.cancelBtn').on("click",function()
        {
            jQuery('#keyword').val('');
            serverData.key ='';
            serverTable.draw();
        });
        jQuery('.saveBtn').on('click',function(){
            if(jQuery("#roleEditForm") && !jQuery("#roleEditForm").Validform({tiptype:3, showAllError:true}).check(false)){
            return;
            };
            var id=jQuery('#id').val();
            var name = jQuery('#name').val();
            var description = jQuery('#description').val();
            var creator =jQuery('#creator').val();
            if(id==''){
            	var d={
                        name:jQuery('#name').val(),
                        description:jQuery('#description').val(),
                        creator:jQuery('#creator').val()
                    };
            	 var api = window.rootPath + "/api/roles";
            	 jQuery.ajax({
                     type: 'post',
                     url: api,
                     data: JSON.stringify(d),
                     dataType: 'json',
                     contentType: 'application/json;charset=utf-8',
                     success: function (data) {
                    	 jQuery('#roleModal').modal('hide');
                         serverTable.draw();
                         
                     }
                 });
            	
            }else{
            	var data={
                        id:jQuery('#id').val(),
                        name:jQuery('#name').val(),
                        description:jQuery('#description').val(),
                        creator:jQuery('#creator').val()
                    };
            	 var url=window.rootPath+'/api/roles/'+data.id;
            	 jQuery.ajax({
                     url:encodeURI(url),
                     type:'patch',
                     data:JSON.stringify(data),
                     dataType:'json',
                     contentType:'application/json;charset=utf-8',
                     success: function () {
                         jQuery('#roleModal').modal('hide');
                         serverTable.draw(false);
                     }
                 });
            } 
           
        });

    });
})();